package com.jiuyin.dianjing.ui.activity.base;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.api.helper.ApiHelper;
import com.jiuyin.dianjing.api.interfaces.ProgressDialogCallback;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.jiguang.TagAliasOperatorHelper;
import com.jiuyin.dianjing.permission.XPermission;
import com.jiuyin.dianjing.ui.activity.container.ContainerActivity;
import com.jiuyin.dianjing.ui.activity.login.LoginActivity;
import com.jiuyin.dianjing.util.IMEUtil;
import com.jiuyin.dianjing.util.PMUtil;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.jpush.im.android.api.JMessageClient;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

import static com.jiuyin.dianjing.jiguang.TagAliasOperatorHelper.ACTION_DELETE;
import static com.jiuyin.dianjing.jiguang.TagAliasOperatorHelper.sequence;


public abstract class BaseActivity extends AppCompatActivity {
    private Context mContext;
    private Unbinder mUnBinder;
    private ProgressDialog mDialog;
    protected ProgressDialogCallback progress = new ProgressDialogCallback() {
        @Override
        public void showProgressDialog() {
            showLoading();
        }

        @Override
        public void dismissProgressDialog() {
            dismissLoading();
        }
    };
    private CompositeDisposable mCompositeDisposable;
    private ImageView btRight;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        beforeSetContentView();
        setContentView(setLayoutId());
        mUnBinder = ButterKnife.bind(this);
        mContext = this;
        doRequestPermissions();
        initData();
        initOthers();
        initView();
    }

    protected void beforeSetContentView() {
    }

    /**
     * set ui layout res id
     *
     * @return res id
     */
    protected abstract int setLayoutId();

    /**
     * 初始化data
     */
    protected abstract void initData();

    /**
     * 初始化UI
     */
    protected abstract void initView();

    protected void initOthers() {
    }

    ;

    /**
     * doRequestPermissions
     */
    protected void doRequestPermissions() {
        XPermission.requestPermissions(this, 101, new String[]{Manifest.permission
                .WRITE_EXTERNAL_STORAGE}, new XPermission.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {

            }

            @Override
            public void onPermissionDenied() {
                XPermission.showTipsDialog(BaseActivity.this);
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 设置标题
     *
     * @param title 标题
     */
    @Override
    public void setTitle(CharSequence title) {
        setTitle(title, true);
    }

    /**
     * 设置标题
     * 考虑没有状态栏
     *
     * @param titleId int
     */
    @Override
    public void setTitle(int titleId) {
        setTitle(titleId, true);
    }

    /**
     * 设置标题
     * 考虑没有状态栏
     *
     * @param titleId int
     */
    public void setTitle(int titleId, boolean visible) {
        TextView tvTitle = findViewById(R.id.tv_title);
        if (null != tvTitle) {
            tvTitle.setText(getString(titleId));
            setBackVisibility(visible);
        }
    }

    /**
     * 设置标题
     * 考虑没有状态栏
     *
     * @param title 标题
     */
    private void setTitle(CharSequence title, boolean visible) {
        TextView tvTitle = findViewById(R.id.tv_title);
        if (null != tvTitle && title != null) {
            tvTitle.setText(title);
            setBackVisibility(visible);
        }
    }

    protected void setRightButton(@DrawableRes int resourceId, View.OnClickListener onClickListener) {
        if (btRight == null) {
            btRight = findViewById(R.id.iv_rightMenu);
        }
        btRight.setImageResource(resourceId);
        btRight.setVisibility(View.VISIBLE);
        if (onClickListener != null) {
            btRight.setOnClickListener(onClickListener);
        }
    }

    protected void setRightButton(@DrawableRes int resourceId, int width, int height, View.OnClickListener onClickListener) {
        if (btRight == null) {
            btRight = findViewById(R.id.iv_rightMenu);
        }
        btRight.setImageResource(resourceId);
        btRight.setVisibility(View.VISIBLE);
        ViewGroup.LayoutParams layoutParams = btRight.getLayoutParams();
        layoutParams.width = width;
        layoutParams.height = height;
        btRight.setLayoutParams(layoutParams);
        if (onClickListener != null) {
            btRight.setOnClickListener(onClickListener);
        }
    }

    protected void setRightButtonVisible(boolean visible) {
        if (btRight == null) {
            btRight = findViewById(R.id.iv_rightMenu);
        }
        if (visible) {
            btRight.setVisibility(View.VISIBLE);
        } else {
            btRight.setVisibility(View.GONE);
        }
    }

    /**
     * 设置返回按钮是否可见
     *
     * @param visibility boolean
     */
    private void setBackVisibility(boolean visibility) {
        View ivBack = findViewById(R.id.iv_back);
        ivBack.setVisibility(visibility ? View.VISIBLE : View.GONE);
        ivBack.setOnClickListener(v -> onBackPressed());
    }

    protected ApiHelper getApiHelper() {
        return ApiHelper.getInstance(this);
    }

    /**
     * 设置App字体不跟随系统字体改变
     *
     * @return
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    protected void onDestroy() {
        mUnBinder.unbind();
        dispose();
        super.onDestroy();
    }

    protected void goTargetActivity(Class<?> cls) {
        goTargetActivity(cls, null);
    }

    protected void goTargetActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(mContext, cls);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        IMEUtil.hideInputMethod(this);
        startActivity(intent);
    }

    public void showLoading() {
        if (mDialog != null && mDialog.isShowing()) {
            return;
        }
        mDialog = new ProgressDialog(this);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mDialog.setMessage(getString(R.string.progress_tips_def));
        mDialog.show();
    }

    public void dismissLoading() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    public void addDisposable(Disposable disposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(disposable);
    }

    public void dispose() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
    }

    /**
     * Android M 全局权限申请回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        XPermission.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 退出,跳转到登录
     */
    protected void quitAndLogin() {
        jPushDeleteAlias();
        jMessageQuit();
        HelperApplication.quitLogin();
        PMUtil.getInstance().finishAllAC();
        Context context = HelperApplication.getContext();
        Intent intent = new Intent(context, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 删除极光alias
     */
    protected void jPushDeleteAlias() {
        TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
        tagAliasBean.action = ACTION_DELETE;
        sequence++;
        tagAliasBean.alias = HelperApplication.getUserId();
        tagAliasBean.isAliasAction = true;
        TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(), sequence, tagAliasBean);
    }

    /**
     * 极光IM退出登录
     */
    private void jMessageQuit() {
        JMessageClient.logout();
    }

    /**
     * 跳转容器页面
     *
     * @param canonicalName 规范名 : Fragment.class.getCanonicalName()
     */
    public void startContainerActivity(String canonicalName) {
        startContainerActivity(canonicalName, null);
    }

    /**
     * 跳转容器页面
     *
     * @param canonicalName 规范名 : Fragment.class.getCanonicalName()
     * @param bundle        跳转所携带的信息
     */
    public void startContainerActivity(String canonicalName, Bundle bundle) {
        Intent intent = new Intent(this, ContainerActivity.class);
        intent.putExtra(ContainerActivity.FRAGMENT, canonicalName);
        if (bundle != null) {
            intent.putExtra(ContainerActivity.BUNDLE, bundle);
        }
        startActivity(intent);
    }
}
